package com.umfwechat.h5.controller.settlement;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.constant.MsgConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.ResultJsonUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AppChannel;
import com.umpay.sp.service.account.remote.AccountServiceRemote;
import com.umpay.sp.service.saas.remote.AppChannelServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.util.AmountUtil;

/**
 * 收入结算：
 * 待结算金额
 * 商户类型（是否有提前结算能力）
 * 提前结算产品是否开通
 * @author css
 *
 */
@Controller
@RequestMapping("h5/settleAmountController")
public class SettleAmountController {
	
	private static Logger logger = LoggerFactory.getLogger(SettleAmountController.class);
	
	//店铺部署详情列表接口
	@Resource
	StoreInfServiceRemote storeInfServiceRemote;
	
	//查询商户待结算金额接口
	@Resource
	AccountServiceRemote accountServiceRemote;
	
	//查询渠道信息接口
	@Resource
	private AppChannelServiceRemote appChannelServiceRemote;
	/**
	 * 查询商户待结算总额、商户类型及提前结算产品开通状态
	 * @param request
	 * @param response
	 * @return
	 */
 	@RequestMapping(value="/queryAmount",method = {RequestMethod.POST,RequestMethod.GET },produces="text/html;charset=UTF-8")
 	@ResponseBody
	public String queryAmount(HttpServletRequest request ,HttpServletResponse response ){
		logger.info("【查询商户待结算金额及商户类型接口】开始");
		String merId = CommonConsts.SPACE;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			if(request.getSession().getAttribute(CommonConsts.MERID) != null){
				merId = request.getSession().getAttribute(CommonConsts.MERID).toString();
			}
			if(StringUtil.isEmpty(merId)){
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433051);
			}
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~查询账户余额接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			com.umpay.sp.model.common.ReqMessage reqMes = ReqMessageUtil.makeSpReq();
			reqMes.getReqMap().put(CommonConsts.MERID, merId);
			reqMes.getReqMap().put(CommonConsts.ACCTYPE, ValueConsts.STATE_ONE);//查询待结算金额
			logger.info("【查询账户余额接口】入参：" + reqMes);
			com.umpay.sp.model.common.ResMessage resMes = accountServiceRemote.getAllAccInfo(reqMes);
			logger.info("【查询账户余额接口】出参：" + resMes);
			if(!resMes.getRetCode().equals(RetCode.SUCCESS)){
				logger.info("查询账户余额接口失败！");
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433016);
			}
			String balance = resMes.getValue(CommonConsts.BALANCE).toString();
			logger.info("查询账户余额为，balance：" + balance);
			//分转元
			balance = AmountUtil.Cent2Dollar(balance);
			//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~店铺部署详情列表接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			ReqMessage req = ReqMessageUtil.makeSpReq();
			req.getReqMap().put(CommonConsts.MERID, merId);
			req.getReqMap().put(CommonConsts.STORETYPE, ValueConsts.ZERO);//店铺类型为小微商
			logger.info("【查询店铺部署详情列表接口】入参：" + req);
			ResMessage res = storeInfServiceRemote.getStoreInfList(req);
			logger.info("【查询店铺部署详情列表接口】出参：" + res);
			if(!res.getRetCode().equals(RetCode.SUCCESS)){
				logger.info("查询店铺部署详情列表接口失败！");
				return ResultJsonUtil.resultJson(RetCode.SUCCESS, MsgConsts.E00433003);
			}
			String totalSize = res.getResMap().get(CommonConsts.TOTAL_SIZE).toString();
			logger.info("店铺类型为小微商的店铺总数为，totalSize：" + totalSize);
			//判断商户是否含有小微商类型店铺
			int total = Integer.parseInt(totalSize);
			String type = null;
			if(total < 0 || total == 0){//标记主商户类型为个体商户，有提前结算能力
				type = ValueConsts.TYPE_ONE;
				//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~查询渠道开通查询接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
				com.umpay.sp.model.common.ReqMessage reqMe = ReqMessageUtil.makeSpReq();	
				Map<String, String> reqM = new HashMap<String, String>();
				reqM.put(CommonConsts.APPSYSID, merId);
				reqM.put(CommonConsts.PRODUCTID, UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_ADVANCESETTLE));
				reqMe.setReqMap(reqM);
				logger.info("【查询渠道开通查询接口】入参：" + reqMe);
				com.umpay.sp.model.common.ResMessage resMe = appChannelServiceRemote.queryByAppSysId(reqMe);
				logger.info("【查询渠道开通查询接口】出参：" + resMe);
				String ktState = CommonConsts.SPACE;
				if(!resMe.getRetCode().equals(RetCode.SUCCESS)){
					if(resMe.getRetCode().equals(RetCode.MER_NOT_EXIST)){		//产品为空
						logger.info("查询渠道开通接口：未获取到商铺对应产品");
						ktState = ValueConsts.ZERO;	//标记提前结算产品未开通
						resultMap.put(CommonConsts.MERID, merId);
						resultMap.put(CommonConsts.BALANCE, balance);
						resultMap.put(CommonConsts.TYPE, type);
						resultMap.put(CommonConsts.KTSTATE, ktState);
						return ResultJsonUtil.resultJson(RetCode.SUCCESS, MsgConsts.E00433120 ,resultMap);
					}
					logger.info("查询渠道开通接口失败");
					return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433016 );
				}
				AppChannel appChannel = (AppChannel) resMe.getValue(CommonConsts.APPCHANNEL);
				Integer state = appChannel.getState();
				logger.info("获取到的state为：" + state);
				if(state == null ){
					logger.info("获取到的state为空");
					resultMap.put(CommonConsts.MERID, merId);
					resultMap.put(CommonConsts.BALANCE, balance);
					resultMap.put(CommonConsts.TYPE, type);
					resultMap.put(CommonConsts.KTSTATE, ktState);
					return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433121 );
				}
				if(state == 3){
					ktState = ValueConsts.STATE_ONE;	//标记提前结算产品已开通
				}
				if(state != 3){
					ktState = ValueConsts.ZERO;	//标记提前结算产品未开通
				}
				resultMap.put(CommonConsts.KTSTATE, ktState);
			}
			if(total > 0){
				//标记主商户类型为小微商，提前结算能力
				type = ValueConsts.ZERO;
			}
			//封装json响应
			resultMap.put(CommonConsts.MERID, merId);
			resultMap.put(CommonConsts.BALANCE, balance);
			resultMap.put(CommonConsts.TYPE, type);
			return ResultJsonUtil.resultJson(RetCode.SUCCESS, MsgConsts.I00433115 , resultMap );
		} catch (Exception e) {
			logger.info("查询商户待结算金额失败！");
		}
		return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433002);
	}
	
}
